package cn.ecpay.unionpay.settle.controller;

import cn.ecpay.unionpay.settle.Common.CommonUtil;
import cn.ecpay.unionpay.settle.Common.RespCode;
import cn.ecpay.unionpay.settle.util.CommonBase;
import cn.ecpay.unionpay.settle.util.FsasService;
import cn.ecpay.unionpay.settle.util.LogUtil;
import cn.ecpay.unionpay.settle.util.SDKConfig;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 历史余额查询
 * Created by zhaoyanzeng on 2018/11/6.
 */
@RestController
public class HisBalanceQueryController {

    @RequestMapping(value = "/hisBalanceQuery", method = RequestMethod.POST)
    public String hisBalanceQuery(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        Map<String, String> contentData = convertContentData(req);

        /**对请求参数进行签名并发送http post请求，接收同步应答报文**/
        Map<String, String> reqData = FsasService.sign(contentData, CommonBase.encoding);			//报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
        String requestBackUrl = SDKConfig.getConfig().getBackRequestUrl();   			//交易请求url从配置文件读取对应属性文件fsas_sdk.properties中的 fsassdk.backTransUrl
        Map<String, String> rspData = FsasService.doPost(reqData,requestBackUrl, CommonBase.encoding); //发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过

        /**对应答码的处理，请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/
        //应答码规范参考open.unionpay.com帮助中心 下载  产品接口规范  《平台接入接口规范-第5部分-附录》
        StringBuffer parseStr = new StringBuffer("");
        if(!rspData.isEmpty()){
            if(FsasService.validate(rspData, CommonBase.encoding)){
                LogUtil.writeLog("验证签名成功");
                String respCode = rspData.get("respCode") ;
                if(RespCode.RESP_SUCCESS.equals(respCode)){
                    //成功
                    //TODO
                }else{
                    //其他应答码为失败请排查原因
                    //TODO
                }
            }else{
                LogUtil.writeErrorLog("验证签名失败");
                //TODO 检查验证签名失败的原因
            }
        }else{
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
        }
        String reqMessage = CommonBase.genHtmlResult(reqData);
        String rspMessage = CommonBase.genHtmlResult(rspData);
        return "历史余额查询交易请求报文:<br/>"+reqMessage+"<br/>" + "应答报文:</br>"+rspMessage+parseStr;
    }


    private Map<String, String> convertContentData(HttpServletRequest req) {
        String acqInsCode = req.getParameter("acqInsCode");
        String txnNo = req.getParameter("txnNo");
        String txnDate = req.getParameter("txnDate");
        String acctDate = req.getParameter("acctDate");
        String acctNo = req.getParameter("acctNo");

        Map<String, String> contentData = new HashMap<String, String>();

        /***银联资金结算接入系统，产品参数，除了encoding自行选择外其他不需修改***/
        contentData.put("version", CommonBase.version);                  //版本号
        contentData.put("encoding", CommonBase.encoding);             //字符集编码 可以使用UTF-8,GBK两种方式
        contentData.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        contentData.put("txnType", "42");                                   //交易类型 42-历史余额查询

        contentData.put("acqInsCode", acqInsCode);                        //机构代码
        contentData.put("txnNo", txnNo);                                    //交易流水号
        contentData.put("txnDate",txnDate);                               //交易日期
        contentData.put("sndTime", CommonBase.getSendTime());      //发送时间 格式HHmmss

        contentData.put("acctDate", acctDate);                                    //银联记账日期
        contentData.put("acctNo", acctNo);                                    //虚拟帐号
        contentData.put("currencyCode", "156");                                    //币种
        return contentData;
    }
}
